/*******************************************************************************
 * Copyright (c) 2014-10-7 @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a>.
 * All rights reserved.
 *
 * Contributors:
 *     <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> - initial API and implementation
 ******************************************************************************/
package com.foreveross.project.projectonline.service;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> 
 * @since 2014-10-7
 */
@SuppressWarnings("unchecked")
public class RBACDomain {

	/**
	 * Can add user & change password.
	 */
	private static final String ROLE_SUPER = "SUPER";
	/**
	 * Can operate all operations.
	 */
	private static final String ROLE_ADMIN = "ADMIN";
	private static RBACDomain me = new RBACDomain();

	public static RBACDomain me() {
		return me;
	}

	/**
	 * Can add user & change password.
	 * @param roleNames
	 * @return
	 * @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> 
	 * @since 2014-10-7
	 */
	public boolean isSuper(Object roleNames) {
		return expect(roleNames, ROLE_SUPER);
	}

	/**
	 * Can operate all operations.
	 * @param roleNames
	 * @return
	 * @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> 
	 * @since 2014-10-7
	 */
	public boolean isAdmin(Object roleNames) {
		return expect(roleNames, ROLE_ADMIN);
	}

	boolean expect(Object roleNames, String expect) {
		if (roleNames == null) {
			return false;
		}
		if (roleNames instanceof String) {
			return expect.equals(roleNames);
		}
		if (roleNames instanceof List) {
			for (Object list : (List) roleNames) {
				if (roleNames == null) {
					continue;
				}
				if (expect.equals(list)) {
					return true;
				}
			}
		}
		if (roleNames instanceof Map) {
			return ((Map) roleNames).containsKey(expect);
		}
		if (roleNames instanceof Set) {
			return ((Set) roleNames).contains(roleNames);
		}
		return ROLE_SUPER.equals(roleNames);
	}
}
